﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Text.RegularExpressions;
using DevExpress.XtraEditors;
using MixingStation.LTWebService;
using System.Diagnostics;
using Newtonsoft.Json;

namespace MixingStation
{
    public partial class MaterielInfoUC : UserControl
    {
        //是否联网
        private bool m_IsOnline = true;
        private List<materialWS> m_MaterialList = new List<materialWS>();
        private List<supplierWS> m_SupplierList = new List<supplierWS>();
        private List<placeWS> m_PlaceList = new List<placeWS>();
        private List<DirectionInfo> m_DirectionList = new List<DirectionInfo>();
        private List<ReceiveInfo> m_ReceiveList = new List<ReceiveInfo>();

        private decimal m_CurrentWeight = 0;
        //车牌号
        private string m_CurrentCarCode = "";
        //货物代码
        private string m_MaterialCode = "";
        //供应商
        private string m_SupplierCode = "";
        //产地
        private string m_PlaceCode = "";
        //流向
        private string m_DirectionCode = "";
        //收货单位
        private string m_ReceiveCode = "";

        //称重类型
        private WeightWayEnum m_PurchaseType = WeightWayEnum.Purchase;
        public WeightWayEnum PurchaseType
        {
            set { m_PurchaseType = value; }
        }

        //称重类型
        private WeightTypeEnum m_WeightWay = WeightTypeEnum.Auto;
        public WeightTypeEnum WeightWay
        {
            set { m_WeightWay = value; }
        }

        //选择的订单
        private purchaseOrderWS m_SelectedPurchaseOrder = null;
        //是否默认选择区域
        private bool m_IsDefaultCarArea = false;
        //当前车辆的上传状态
        private int m_CurrentUploadedStatus = (int)UploadedEnum.UnUploaded;
        //当前加载的SYstemId
        private long m_CurrentSystemId = -1;
        //可以输入送货重量的物料编码list
        private List<string> m_DeliveryCodeList = new List<string>();
        //所属公司
        private long m_BelongCorpId = 2;
        //记录第一次称重的过磅时间
        private DateTime m_FirstWeightTime = DateTime.MinValue;
        public MaterielInfoUC()
        {
            InitializeComponent();
        }
        private userWs m_CurrentUser = null;

        public void InitMaterialInfoUC(userWs user, List<materialWS> materialList, List<supplierWS> supplierList,
            List<placeWS> placeList, List<DirectionInfo> directionList,  List<ReceiveInfo> receiveList, long belongCorpId, List<string> deliveryCodeList)
        {
            m_CurrentUser = user; 
            m_MaterialList = materialList;
            m_SupplierList = supplierList;
            m_PlaceList = placeList;
            m_DirectionList = directionList;
            m_ReceiveList = receiveList;
            txtWeightStatus.Text = "第一次称重";
            m_BelongCorpId = belongCorpId;
            m_DeliveryCodeList = deliveryCodeList;

            Stopwatch sw = new Stopwatch();
            sw.Start();
            InitCarArea();
            InitMaterialInfo();
            InitSupplierInfo();
            InitPlaceInfo();
            InitDirectionInfo();
            //InitBuckleReasons();
            InitReceiveInfo();
            sw.Stop();
            LogHelper.info("界面开始加载时初始化InitMaterialInfoUC耗时：" + sw.ElapsedMilliseconds);
        }

        #region 对外方法
        //清空界面
        public void ClearForm()
        {
            txtIsDefaultTare.Text = "";
            txtWeightStatus.Text = "第一次称重";
            if (m_IsDefaultCarArea)
                cmbCarArea.SelectedIndex = 0;
            else
                cmbCarArea.Text = "";
            cmbCarCode.SelectedIndex = -1;
            cmbSupplier.SelectedIndex = -1;
            cmbMaterial.SelectedIndex = -1;
            cmbPlace.SelectedIndex = -1;
            cmbDirection.SelectedItem = 
                CommonHelper.FindDataInfoByKey(cmbDirection, m_DefaultDirectionCode);
            cmbDirection.Properties.ReadOnly = true;
            cmbReceive.SelectedIndex = -1;
            cmbReceive.Properties.ReadOnly = true;

            spBuckleRate.Value = 0;
            btnOrder.Text = "";
            m_SelectedPurchaseOrder = null;
            cmbBuckleReasons.Text = "";
            txtRemark.Text = "";
            txtFirstWeight.Text = "0";
            txtGrossWeight.Text = "0";
            txtTareWeight.Text = "0";
            txtBuckleWeight.Text = "0";
            txtDefaultWeight.Text = "0";
            txtNetWeight.Text = "0";
            txtDeliveryWeight.Text = "0"; 
            txtDeliveryWeight.Properties.ReadOnly = true;
            this.rgpBuckleType.SelectedIndex = 0;
            m_FirstWeightTime = DateTime.MinValue;
        }

        public void SetNoUseStatus()
        {
            cmbCarArea.Properties.ReadOnly = true;
            cmbCarCode.Properties.ReadOnly = true;
            cmbSupplier.Properties.ReadOnly = true;
            cmbMaterial.Properties.ReadOnly = true;
            cmbPlace.Properties.ReadOnly = true;
            cmbDirection.Properties.ReadOnly = true;
            cmbReceive.Properties.ReadOnly = true;
            spBuckleRate.Properties.ReadOnly = true;
            cmbBuckleReasons.Properties.ReadOnly = true;
            txtRemark.Properties.ReadOnly = true;
            btnOrder.Enabled = false;
        }

        //刷新状态未完成的车辆车牌号
        public void RefreshUnCompletedCarCode(List<string> carCodeList)
        {
            try
            {
                cmbCarCode.Properties.Items.Clear();
                cmbCarCode.Properties.Items.Add("");
                foreach (string carCode in carCodeList)
                    cmbCarCode.Properties.Items.Add(carCode);
            }
            catch (Exception ex)
            {
                LogHelper.error("加载未完结的车牌信息异常：" + ex.Message);
            }
        }

        //获取界面信息
        public WeightRecordInfo GetMaterialFormInfo()
        {
            WeightRecordInfo info = new WeightRecordInfo();
            try
            {
                info.IsDefaultTare = this.txtIsDefaultTare.Text == "是" ? true : false;
                info.OrderCode = btnOrder.Text.Trim();
                info.PurchaseOrder = m_SelectedPurchaseOrder;
                string tempCarCode = cmbCarArea.Text.Trim() + " " + cmbCarCode.Text.Trim();
                if (tempCarCode.Length == 8)
                    tempCarCode += "..";
                else if (tempCarCode.Length == 9)
                    tempCarCode += ".";
                info.CarCode = IsCarCodeValidate(tempCarCode) == true ? tempCarCode : "";
                info.MaterialCode = m_MaterialCode;
                info.MaterialName = this.cmbMaterial.Text.Trim();
                info.SupplierCode = m_SupplierCode;
                info.SupplierName = this.cmbSupplier.Text.Trim();
                info.PlaceCode = m_PlaceCode;
                info.PlaceName = this.cmbPlace.Text.Trim();
                info.DirectionCode = m_DirectionCode;
                info.DirectionName = this.cmbDirection.Text.Trim();
                info.ReceiveCode = m_ReceiveCode;
                info.ReceiveName = cmbReceive.Text.Trim();
                info.IsFirstWeight = txtWeightStatus.Text == "第一次称重" ? true : false;
                info.TempWeight = int.Parse(txtFirstWeight.Text.Trim());
                info.GrossWeight = int.Parse(txtGrossWeight.Text.Trim());
                info.TareWeight = int.Parse(txtTareWeight.Text.Trim());
                info.DefaultTareWeight = int.Parse(txtDefaultWeight.Text.Trim());
                info.BuckleWeight = int.Parse(txtBuckleWeight.Text.Trim());
                info.NetWeight = info.IsFirstWeight == true ? 0 : (info.GrossWeight - info.TareWeight - info.BuckleWeight);
                info.BuckleReasons = cmbBuckleReasons.Text.Trim();
                info.Remark = txtRemark.Text.Trim();
                info.UploadStatus = m_CurrentUploadedStatus;
                info.SystemId = m_CurrentSystemId;
                info.DeliveryWeight = int.Parse(this.txtDeliveryWeight.Text.Trim());
                info.FirstWeightTime = m_FirstWeightTime;
            }
            catch (Exception ex)
            {
                LogHelper.error("获取界面信息异常：" + ex.ToString());
            }
            return info;
        }

        //设置称重信息
        public void FillWeightInfo(decimal tempWeight, decimal grossWeight, decimal tareWeight)
        {
            this.txtFirstWeight.Text = tempWeight.ToString();
            this.txtGrossWeight.Text = grossWeight.ToString();
            this.txtTareWeight.Text = tareWeight.ToString();
            decimal buckleWeight = decimal.Parse(this.txtBuckleWeight.Text.Trim());
            decimal netWeight = 0;
            if (tareWeight > 0)
                netWeight = grossWeight - tareWeight - buckleWeight;
            this.txtNetWeight.Text = netWeight.ToString();
        }

        //委托
        public delegate void ShowInfoHandler(string txt);
        //事件
        public event ShowInfoHandler OnShowInfoEvent;

        //设置上称重量
        public void SetCurrentWeight(decimal currentWeight)
        {
            m_CurrentWeight = currentWeight;
        }

        //刷新重量信息显示
        public void RefreshWeightShow(decimal currentWeight, int type)
        {
            try
            {
                if (type == (int)WeightTypeEnum.Auto)
                {
                    if (txtWeightStatus.Text == "第二次称重")
                    {
                        decimal tempWeight = decimal.Parse(txtFirstWeight.Text.Trim());
                        if (m_PurchaseType == WeightWayEnum.Purchase)
                        {
                            this.txtTareWeight.Text = currentWeight.ToString();
                        }
                        else
                        {
                            if (tempWeight > currentWeight)
                            {
                                this.txtGrossWeight.Text = tempWeight.ToString();
                                this.txtTareWeight.Text = currentWeight.ToString();
                            }
                            else
                            {
                                this.txtGrossWeight.Text = currentWeight.ToString();
                                this.txtTareWeight.Text = tempWeight.ToString();
                            }
                        }
                        decimal grossWeight = decimal.Parse(this.txtGrossWeight.Text.Trim());
                        decimal tareWeight = decimal.Parse(this.txtTareWeight.Text.Trim());
                        decimal buckleWeight = 0;
                        //扣杂变化
 
                        if (grossWeight > 0 && tareWeight > 0)
                        {
                            if (rgpBuckleType.SelectedIndex == 0)
                            {
                                decimal buckleRate = spBuckleRate.Value * (decimal)0.01;
                                buckleWeight = (grossWeight - tareWeight) * buckleRate;
                                this.txtBuckleWeight.Text = buckleWeight.ToString("0");
                            }
                            else
                            {
                                buckleWeight = decimal.Parse(this.txtBuckleWeight.Text.Trim());
                                decimal buckleRate = buckleWeight / (grossWeight - tareWeight);
                                spBuckleRate.EditValue = buckleRate * 100;
                            }
                        }
                        decimal netWeight = grossWeight - tareWeight - buckleWeight;
                        this.txtNetWeight.Text = netWeight.ToString("0");
                    }
                    else if (txtIsDefaultTare.Text == "是")
                    {
                        this.txtFirstWeight.Text = currentWeight.ToString("0");
                        this.txtGrossWeight.Text = currentWeight.ToString("0");
                        decimal tareWeight = decimal.Parse(this.txtTareWeight.Text.Trim());

                        decimal buckleWeight = 0;
                        if (rgpBuckleType.SelectedIndex == 0)
                        {
                            decimal buckleRate = spBuckleRate.Value * (decimal)0.01;
                            buckleWeight = (currentWeight - tareWeight) * buckleRate;
                            this.txtBuckleWeight.Text = buckleWeight.ToString("0");
                        }
                        else
                        {
                            buckleWeight = decimal.Parse(this.txtBuckleWeight.Text.Trim());
                            decimal buckleRate = buckleWeight / (currentWeight - tareWeight);
                            spBuckleRate.EditValue = buckleRate * 100;
                        }
                        this.txtNetWeight.Text = (currentWeight - tareWeight - buckleWeight).ToString("0");
                    }
                }
                else
                {
                    this.txtFirstWeight.Text = currentWeight.ToString("0");
                    this.txtGrossWeight.Text = currentWeight.ToString("0");
                    decimal tareWeight = decimal.Parse(this.txtTareWeight.Text.Trim());

                    decimal buckleWeight = 0;
                    if (rgpBuckleType.SelectedIndex == 0)
                    {
                        decimal buckleRate = spBuckleRate.Value * (decimal)0.01;
                        buckleWeight = (currentWeight - tareWeight) * buckleRate;
                        this.txtBuckleWeight.Text = buckleWeight.ToString("0");
                    }
                    else
                    {
                        buckleWeight = decimal.Parse(this.txtBuckleWeight.Text.Trim());
                        decimal buckleRate = buckleWeight / (currentWeight - tareWeight);
                        spBuckleRate.EditValue = buckleRate * 100;
                    }
                    this.txtNetWeight.Text = (currentWeight - tareWeight - buckleWeight).ToString("0");
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("实时刷新界面称重信息异常：" + ex.ToString());
            }
          
        }

        //设置网络状态
        public void SetNetWorkStatus(bool isOn)
        {
            m_IsOnline = isOn;
        }

        //自动除皮时若该物料有扣杂比例，需更新显示扣杂，上称重量和毛重为当前重量，皮重为基准皮重
        public void UpdateBuckleWeightShow(bool isOnce)
        {
            if (isOnce)
            {
                decimal defaultWeight = decimal.Parse(txtDefaultWeight.Text.Trim());
                FillWeightInfo(m_CurrentWeight, m_CurrentWeight, defaultWeight);
                spBuckleRate_EditValueChanged(null, null);
            }
            else
            {
                if (this.txtWeightStatus.Text == "第一次称重")
                {
                    this.txtFirstWeight.Text = "0";
                    this.txtGrossWeight.Text = "0";
                    this.txtTareWeight.Text = "0";
                    this.txtBuckleWeight.Text = "0";
                    this.txtNetWeight.Text = "0";
                    this.txtDeliveryWeight.Text = "0";
                }
            }
        }

        //设置订单状态
        public void SetOrderEnable(bool isPurchase)
        {
            this.btnOrder.Enabled = isPurchase;
            //采购类型变化时，需把界面清空，且当采购时，收货单位不可选择
            ClearForm();
            cmbReceive.Properties.ReadOnly = isPurchase;
            cmbDirection.Properties.ReadOnly = isPurchase;
        }
        #endregion

        #region 初始化
        //初始化物料
        private void InitMaterialInfo()
        {
            try
            {
                if (m_MaterialList == null || m_MaterialList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (materialWS material in m_MaterialList)
                    list.Add(new DataInfo { Id = material.code, Value = material.name });
                cmbMaterial.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbMaterial.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("加载物料下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载物料下拉框异常：" + ex.Message);
                }
            }
        }

        //加载供应商
        private void InitSupplierInfo()
        {
            try
            {
                if (m_SupplierList == null || m_SupplierList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (supplierWS supplier in m_SupplierList)
                    list.Add(new DataInfo { Id = supplier.code, Value = supplier.name });
                cmbSupplier.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbSupplier.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("加载供应商下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载供应商下拉框异常：" + ex.Message);
                }
            }     
        }

        //加载产地信息
        private void InitPlaceInfo()
        {
            try
            {
                if (m_PlaceList == null || m_PlaceList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (placeWS place in m_PlaceList)
                    list.Add(new DataInfo { Id = place.code, Value = place.name });
                cmbPlace.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbPlace.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("加载产地下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载产地下拉框异常：" + ex.Message);
                }
            }
        }

        //默认的流向
        private string m_DefaultDirectionCode = "";
        //加载流向信息
        private void InitDirectionInfo()
        {
            try
            {
                if (m_DirectionList == null || m_DirectionList.Count == 0)
                    return;
                var list = new List<DataInfo>();
              
                foreach (DirectionInfo direction in m_DirectionList)
                {
                    if (direction.IsDefault)
                        m_DefaultDirectionCode = direction.Code;
                    list.Add(new DataInfo { Id = direction.Code, Value = direction.Name });
                }
                cmbDirection.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbDirection.Properties.Items.Add(item);
                cmbDirection.SelectedItem = CommonHelper.FindDataInfoByKey(cmbDirection, m_DefaultDirectionCode);
                cmbDirection.Properties.ReadOnly = true;
            }
            catch (Exception ex)
            {
                LogHelper.error("加载流向下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载流向下拉框异常：" + ex.Message);
                }
            }
        }

        private void InitReceiveInfo()
        {
            try
            {
                if (m_ReceiveList == null || m_ReceiveList.Count == 0)
                    return;
                var list = new List<DataInfo>();

                foreach (ReceiveInfo receive in m_ReceiveList)
                    list.Add(new DataInfo { Id = receive.Code, Value = receive.Name });
                cmbReceive.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbReceive.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("加载收货单位下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载收货单位下拉框异常：" + ex.Message);
                }
            }
        }

        //加载扣杂原因
        private void InitBuckleReasons()
        {
            try
            {
                this.cmbBuckleReasons.Properties.Items.Clear();
                string buckleReasonStr = ConfigurationManager.AppSettings["BuckleReasons"].ToString();
                if (!string.IsNullOrEmpty(buckleReasonStr))
                {
                    foreach (string str in buckleReasonStr.Split(','))
                        cmbBuckleReasons.Properties.Items.Add(str);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("加载扣杂原因下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载扣杂原因下拉框异常：" + ex.Message);
                }
            }
        }

        //车牌号区域
        private void InitCarArea()
        {
            try
            {
                this.cmbCarArea.Properties.Items.Clear();
                m_IsDefaultCarArea = ConfigurationManager.AppSettings["IsDefaultCarArea"].ToString() == "1" ? true : false;
                string strArr = ConfigurationManager.AppSettings["CarArea"].ToString();
                if (!string.IsNullOrEmpty(strArr))
                {
                    foreach (string item in strArr.Split(','))
                        cmbCarArea.Properties.Items.Add(item);
                }
                if (m_IsDefaultCarArea)
                    cmbCarArea.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("加载车牌号区域下拉框异常：" + ex.Message);
                if (OnShowInfoEvent != null)
                {
                    OnShowInfoEvent("加载车牌号区域下拉框异常：" + ex.Message);
                }
            }
        }
        #endregion

        #region 下拉框选择事件
        private void cmbMaterial_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMaterial.SelectedItem == null)
            {
                m_MaterialCode = "";
                this.spBuckleRate.Value = 0;
                this.cmbBuckleReasons.Text = "";
                txtDeliveryWeight.Text = "0";
            }
            else
            {
                m_MaterialCode = ((DataInfo)cmbMaterial.SelectedItem).Id;
                decimal buckleRate = 0;
                string buckleReason = "";
                GetBuckleRateByCode(m_MaterialCode, out buckleRate, out buckleReason);
                this.spBuckleRate.Value = buckleRate;
                this.cmbBuckleReasons.Text = buckleReason;
                txtDeliveryWeight.Text = "0";
                if (m_DeliveryCodeList.Contains(m_MaterialCode) && this.txtWeightStatus.Text == "第二次称重")
                {
                    this.txtDeliveryWeight.Properties.ReadOnly = false;
                }
                else
                {
                    this.txtDeliveryWeight.Properties.ReadOnly = true;
                }
            }

        }

        //根据物料编码获取物的默认扣杂比例
        private void GetBuckleRateByCode(string materialCode, out decimal buckleRate, out string buckleReason)
        {
            buckleRate = 0;
            buckleReason = "";
            if (string.IsNullOrEmpty(materialCode))
                return;
            else
            {
                //根据物料Code获取扣杂比例
                string sql = "select DefaultBuckleRate,BuckleReason  from Material where Code = '" + materialCode + "'";
                DataTable dt = CommonHelper.DoSelectOpreation(sql);
                if (dt == null || dt.Rows.Count == 0)
                    return;
                else
                {
                    buckleRate =  decimal.Parse(dt.Rows[0][0].ToString()) * 100;
                    buckleReason = dt.Rows[0][1].ToString();
                }
            }
        }

        private void cmbSupplier_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSupplier.SelectedItem == null)
                m_SupplierCode = "";
            else
                m_SupplierCode = ((DataInfo)cmbSupplier.SelectedItem).Id;
        }

        private void cmbPlace_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPlace.SelectedItem == null)
                m_PlaceCode = "";
            else
                m_PlaceCode = ((DataInfo)cmbPlace.SelectedItem).Id;
        }

        //流向选择事件
        private void cmbDirection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDirection.SelectedItem == null)
                m_DirectionCode = "";
            else
                m_DirectionCode = ((DataInfo)cmbDirection.SelectedItem).Id;
        }

        //收货单位选择变化事件
        private void cmbReceive_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbReceive.SelectedItem == null)
                m_ReceiveCode = "";
            else
                m_ReceiveCode = ((DataInfo)cmbReceive.SelectedItem).Id;
        }

        private void cmbCarCode_SelectedIndexChanged(object sender, EventArgs e)
       {
            //车牌号选择变化后加载第一次称重的相关信息
           if (cmbCarCode.SelectedItem == null)
                return;
            string carCode = cmbCarCode.SelectedItem.ToString();
            if (!IsCarCodeValidate(carCode))
                return;
            if (string.IsNullOrEmpty(carCode))
            {
                this.ClearForm();
                return;
            }
            //根据车牌号获取该车牌号未完结的单据
            ProcessCarCodeChange(carCode);
        }

        private void cmbCarArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.cmbCarCode.SelectedIndexChanged -= new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
            if (cmbCarArea.Text.Length < 2)
            {
                cmbCarArea.Focus();
                cmbCarArea.SelectionStart = cmbCarArea.Text.Length;
            }
            else if (cmbCarArea.Text.Length == 2)
            {
                cmbCarCode.Text = "";
                cmbCarCode.Focus();
                cmbCarCode.SelectionStart = 0;
            }
            this.cmbCarCode.SelectedIndexChanged += new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
        }
        #endregion

        //输入车牌号，若是第一次称重，则将该车上一次的信息加载出来，包括物料供应商产地等信息
        private void cmbCarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            //输入的字母为大写
            e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper());
            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || e.KeyChar == 8)
                {
                    e.Handled = false;
                }
                else
                {
                    if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || e.KeyChar == 8)
                    {
                        e.Handled = false;
                    }
                    else e.Handled = true;
                }
            }
            //回车加载信息，若为第一次称重则加载上一次的信息，若为第二次称重，则加载之前过磅的信息
            if (e.KeyChar != 13)
                return;
            string carCode = cmbCarArea.Text.Trim() + " " + cmbCarCode.Text.Trim();
            //判断车牌号是否合法
            if (!IsCarCodeValidate(carCode))
            {
                if (OnShowInfoEvent != null)
                {
                    LogHelper.error("车牌号：" + carCode + "输入不合法!");
                    OnShowInfoEvent("车牌号不合法,请重新输入!");
                }
                return;
            }
            ProcessCarCodeChange(carCode);
        }

        private void ProcessCarCodeChange(string carCode)
        {
            carWS car = null;
            if (m_IsOnline && m_PurchaseType == WeightWayEnum.Purchase)
            {
                car = ServerCommonHelper.GetCar(carCode, 2, m_BelongCorpId);
                if (car != null)
                {
                    //若该车辆有固定皮重，更新基准皮重
                    this.txtDefaultWeight.Text = car.tare.ToString("0");
                    if (car.isDefaultTare)
                    {
                        txtIsDefaultTare.Text = "是";
                        this.txtFirstWeight.Text = m_CurrentWeight.ToString("0");
                        this.txtGrossWeight.Text = m_CurrentWeight.ToString("0");
                        this.txtTareWeight.Text = this.txtDefaultWeight.Text;
                    }
                    else
                    {
                        txtIsDefaultTare.Text = "否";
                    }
                }
            }
            //根据车牌号到称重记录表里查询是否有该车辆未完结的信息，若有，则为二次过磅，
            //若没有，则到历史记录表里查询，加载历史车辆信息
            bool isPurchase = m_PurchaseType == WeightWayEnum.Purchase ? true : false;
            List<WeightRecordInfo> recordInfoList = GetUnCompletedWeightInfo(carCode, isPurchase);
            if (recordInfoList == null || recordInfoList.Count == 0)
            {
                if (m_IsOnline)
                {
                    if (m_PurchaseType == WeightWayEnum.Purchase)
                    {
                        purchaseCardWS before = null;
                        try
                        {
                            before = ServerCommonHelper.GetPurchaseCardBefore(car.id);
                        }
                        catch
                        {
                        }
                        if (before != null)
                            LoadLastWeightRecordInfo(before);
                        else
                        {
                            this.cmbMaterial.SelectedIndex = -1;
                            this.cmbSupplier.SelectedIndex = -1;
                            this.cmbPlace.SelectedIndex = -1;
                        }
                        //有网状态下默认弹出订单选择界面
                        this.btnOrder_ButtonClick(null, null);
                    }
                    else
                    {
                        //获取非采购物资上一次来的时候过磅信息
                        try
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            dic.Add("carCode", carCode);
                            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                            WeightRecordInfo record = ServerCommonHelper.GetLastWeightRecordByCarCode(m_CurrentUser.userame, m_CurrentUser.password);
                            if (record != null)
                            {
                                cmbSupplier.SelectedItem = CommonHelper.FindDataInfoByKey(cmbSupplier, record.SupplierCode);
                                cmbMaterial.SelectedItem = CommonHelper.FindDataInfoByKey(cmbMaterial, record.MaterialCode);
                                cmbPlace.SelectedItem = CommonHelper.FindDataInfoByKey(cmbPlace, record.PlaceCode);
                                cmbDirection.SelectedItem = CommonHelper.FindDataInfoByKey(cmbDirection, record.DirectionCode);
                            }
                            else
                            {
                                this.cmbMaterial.SelectedIndex = -1;
                                this.cmbSupplier.SelectedIndex = -1;
                                this.cmbPlace.SelectedIndex = -1;
                                //this.cmbDirection.SelectedIndex = 0;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.error("车牌号：" + carCode + "获取最近一次过磅记录异常：" + ex.Message);
                            OnShowInfoEvent("车牌号：" + carCode + "获取最近一次过磅记录异常：" + ex.Message);
                            return;
                        }
                    }
                }
            }
            else if (recordInfoList.Count >= 2)
            {
                if (OnShowInfoEvent != null)
                {
                    LogHelper.error("车牌号：" + carCode + "获取多条未完结的记录!");
                    OnShowInfoEvent("该车牌号获取多条未完结记录!");
                    return;
                }
            }
            else if (recordInfoList.Count == 1)
            {
                //即二次过磅，加载改车一次过磅的信息
                LoadWeightRecordInfo(recordInfoList[0]);
                //更新重量信息
                RefreshWeightShow(m_CurrentWeight, (int)WeightTypeEnum.Auto);
            }
        }

        private void cmbCarCode_TextChanged(object sender, EventArgs e)
        {
            string carCode = cmbCarArea.Text.Trim() + " " + cmbCarCode.Text.Trim();
            if (!IsCarCodeValidate(carCode))
                return;
            if (carCode.Length == 8)
                carCode += "..";
            else if (carCode.Length == 9)
                carCode += ".";
            ProcessCarCodeChange(carCode);
        }

        //扣杂比例不为负数
        private void spBuckleRate_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue != null && e.NewValue.ToString().StartsWith("-"))
            {
                e.Cancel = true;
            }
        }

        //扣杂比例变化时重量显示变化
        private void spBuckleRate_EditValueChanged(object sender, EventArgs e)
        {
            if (rgpBuckleType.SelectedIndex == 1)
                return;
            //判断是否为自动除皮或者一次称重
            if (m_WeightWay == WeightTypeEnum.OnceWeight)
            {
                this.txtFirstWeight.Text = m_CurrentWeight.ToString();
                this.txtGrossWeight.Text = m_CurrentWeight.ToString();
                this.txtTareWeight.Text = this.txtDefaultWeight.Text.Trim();
            }
            decimal grossWeight = decimal.Parse(this.txtGrossWeight.Text.Trim());
            decimal tareWeight = decimal.Parse(this.txtTareWeight.Text.Trim());
            if (grossWeight <= 0)
                return;
            decimal buckleWeight = 0;
            //扣杂变化
            decimal buckleRate = spBuckleRate.Value * (decimal)0.01;
            buckleWeight = (grossWeight - tareWeight) * buckleRate;
            this.txtBuckleWeight.Text = Math.Round(buckleWeight).ToString("0");
            decimal netWeight = grossWeight - tareWeight - buckleWeight;
            this.txtNetWeight.Text = netWeight.ToString("0");
        }

        //基准皮重变化时扣杂也要实时变化
        private void txtDefaultWeight_TextChanged(object sender, EventArgs e)
        {
            spBuckleRate_EditValueChanged(null, null);
        }

        private void txtBuckleWeight_TextChanged(object sender, EventArgs e)
        {
            if (rgpBuckleType.SelectedIndex == 0)
                return;
            decimal grossWeight = decimal.Parse(this.txtGrossWeight.Text.Trim());
            decimal tareWeight = decimal.Parse(this.txtTareWeight.Text.Trim());
            if (grossWeight <= 0)
                return;
            decimal buckleWeight = 0;
            if (!string.IsNullOrEmpty(this.txtBuckleWeight.Text.Trim()))
                buckleWeight = decimal.Parse(this.txtBuckleWeight.Text.Trim());
            decimal netWeight = grossWeight - tareWeight - buckleWeight;
            this.txtNetWeight.Text = netWeight.ToString("0");
            if ((grossWeight - tareWeight) > 0)
            {
                decimal buckleRate = buckleWeight / (grossWeight - tareWeight);
                this.spBuckleRate.Value = buckleRate * 100;
            }
        }

        //输入的区域为大写字符
        private void cmbCarArea_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.cmbCarCode.SelectedIndexChanged -= new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
            e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper());
            //删除键
            if (e.KeyChar == 8)
                return;
            cmbCarArea.SelectionStart = cmbCarArea.Text.Length;
            cmbCarArea.SelectionLength = 0;
            this.cmbCarCode.SelectedIndexChanged += new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
        }

        //区域输入两个字符后焦点放到车号框
        private void cmbCarArea_TextChanged(object sender, EventArgs e)
        {
            this.cmbCarCode.SelectedIndexChanged -= new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
            if (this.cmbCarArea.Text.Length < 2)
            {
                this.cmbCarArea.Focus();
                this.cmbCarArea.SelectionStart = this.cmbCarArea.Text.Length;
            }
            else if (this.cmbCarArea.Text.Length == 2)
            {
                this.cmbCarCode.Text = "";
                this.cmbCarCode.Focus();
                this.cmbCarCode.SelectionStart = 0;
                cmbCarCode.SelectionLength = 0;
            }
            this.cmbCarCode.SelectedIndexChanged += new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
        }

        #region 私有方法
        //判断车牌号是否正常
        private bool IsCarCodeValidate(string carNumber)
        {
            if (carNumber.Length < 8 || cmbCarCode.Text.Trim().Length < 5)
                return false;
            if (carNumber.Split(' ').Length != 2)
                return false;
            string area = carNumber.Substring(0, 1);
            if (Regex.IsMatch(area, @"[\u4e00-\u9fa5]"))
                return true;
            return false;
        }

        //根据车牌号获取完结的记录信息，若为第一次称重则返回null
        private List<WeightRecordInfo> GetUnCompletedWeightInfo(string carCode, bool isPurchase)
        {
            List<WeightRecordInfo> recordInfoList = new List<WeightRecordInfo>();
            string sqlStr = "select * from WeightRecords where IsCompleted = false and IsPurchase = " + isPurchase + " and CarCode = '" + carCode + "'";
            DataTable recordDT = CommonHelper.DoSelectOpreation(sqlStr);
            if (recordDT == null || recordDT.Rows.Count == 0)
                return recordInfoList;
            try
            {
                foreach (DataRow dr in recordDT.Rows)
                {
                    WeightRecordInfo record = new WeightRecordInfo();
                    record.SystemId = long.Parse(dr["SystemId"].ToString());
                    record.OrderCode = dr["OrderCode"].ToString();
                    record.CarCode = dr["CarCode"].ToString();
                    record.MaterialCode = dr["MaterialCode"].ToString();
                    record.SupplierCode = dr["SupplierCode"].ToString();
                    record.PlaceCode = dr["PlaceCode"].ToString();
                    record.DirectionCode = dr["DirectionCode"].ToString();
                    record.ReceiveCode = dr["ReceiveCode"].ToString();
                    record.TempWeight = dr["TempWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["TempWeight"].ToString());
                    record.GrossWeight = dr["GrossWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["GrossWeight"].ToString());
                    record.TareWeight = dr["TareWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["TareWeight"].ToString());
                    record.BuckleWeight = dr["BuckleWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["BuckleWeight"].ToString());
                    record.BuckleReasons = dr["BuckleReasons"].ToString();
                    record.NetWeight = dr["NetWeight"] == DBNull.Value ? 0 : decimal.Parse(dr["NetWeight"].ToString());
                    record.FirstWeightTime = dr["FirstWeightTime"] == DBNull.Value ? DateTime.MinValue : DateTime.Parse(dr["FirstWeightTime"].ToString());
                    record.FirstWeightman = dr["FirstWeightman"].ToString();
                    record.LastWeightTime = dr["LastWeightTime"] == DBNull.Value ? DateTime.MinValue : DateTime.Parse(dr["LastWeightTime"].ToString());
                    record.LastWeightman = dr["LastWeightman"].ToString();
                    record.IsPrinted = Boolean.Parse(dr["IsPrinted"].ToString());
                    record.IsCompleted = Boolean.Parse(dr["IsCompleted"].ToString());
                    record.UploadStatus = int.Parse(dr["UploadStatus"].ToString());
                    record.Remark = dr["Remark"].ToString();
                    record.IsPurchase = Boolean.Parse(dr["IsPurchase"].ToString());
                    record.IsBack = Boolean.Parse(dr["IsBack"].ToString());
                    recordInfoList.Add(record);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("获取车牌号：" + carCode + "未完结称重信息异常：" + ex.Message);
            }
            return recordInfoList;
        }

        //加载界面称重信息信息
        private void LoadWeightRecordInfo(WeightRecordInfo weightRecord)
        {
            txtWeightStatus.Text = "第二次称重";
            if (weightRecord.UploadStatus != (int)UploadedEnum.UnUploaded)
                btnOrder.Text = weightRecord.OrderCode;
            if (!string.IsNullOrEmpty(weightRecord.CarCode))
            {
                string[] strArr = weightRecord.CarCode.Split(' ');
                if (strArr.Length == 2)
                {
                    cmbCarCode.SelectedIndexChanged -= new System.EventHandler(this.cmbCarCode_SelectedIndexChanged);
                    cmbCarArea.Text = strArr[0];
                    cmbCarCode.Text = strArr[1].TrimEnd('.');
                    cmbCarCode.SelectedIndexChanged += new System.EventHandler(this.cmbCarCode_SelectedIndexChanged); 
                }
            }
            if (!string.IsNullOrEmpty(weightRecord.SupplierCode))
                cmbSupplier.SelectedItem = CommonHelper.FindDataInfoByKey(cmbSupplier, weightRecord.SupplierCode);
            if (!string.IsNullOrEmpty(weightRecord.MaterialCode))
                cmbMaterial.SelectedItem = CommonHelper.FindDataInfoByKey(cmbMaterial, weightRecord.MaterialCode);
            if (!string.IsNullOrEmpty(weightRecord.PlaceCode))
                cmbPlace.SelectedItem = CommonHelper.FindDataInfoByKey(cmbPlace, weightRecord.PlaceCode);
            if (!string.IsNullOrEmpty(weightRecord.DirectionCode))
                cmbDirection.SelectedItem = CommonHelper.FindDataInfoByKey(cmbDirection, weightRecord.DirectionCode);
            if (!string.IsNullOrEmpty(weightRecord.ReceiveCode))
                cmbReceive.SelectedItem = CommonHelper.FindDataInfoByKey(cmbReceive, weightRecord.ReceiveCode);
            txtFirstWeight.Text = weightRecord.TempWeight > 0 ? weightRecord.TempWeight.ToString() : "0";
            txtGrossWeight.Text = weightRecord.GrossWeight > 0 ? weightRecord.GrossWeight.ToString() : "0";
            txtTareWeight.Text = weightRecord.TareWeight > 0 ? weightRecord.TareWeight.ToString() : "0";
            //txtDefaultWeight.Text = weightRecord.DefaultTareWeight > 0 ? weightRecord.DefaultTareWeight.ToString() : "0";
            if (this.spBuckleRate.Value == 0)
            {
                txtBuckleWeight.Text = weightRecord.BuckleWeight > 0 ? weightRecord.DefaultTareWeight.ToString() : "0";
                cmbBuckleReasons.Text = weightRecord.BuckleReasons;
            }
            txtNetWeight.Text = weightRecord.NetWeight > 0 ? weightRecord.NetWeight.ToString() : "0";
            txtRemark.Text = weightRecord.Remark;
            m_CurrentUploadedStatus = weightRecord.UploadStatus;
            m_CurrentSystemId = weightRecord.SystemId;
            m_FirstWeightTime = weightRecord.FirstWeightTime;
        }

        private void LoadLastWeightRecordInfo(purchaseCardWS before)
        {
            if (before.supplier != null)
                cmbSupplier.SelectedItem = CommonHelper.FindDataInfoByKey(cmbSupplier, before.supplier.code);
            if (before.material != null)
                cmbMaterial.SelectedItem = CommonHelper.FindDataInfoByKey(cmbMaterial, before.material.code);
            if (before.place != null)
                cmbPlace.SelectedItem = CommonHelper.FindDataInfoByKey(cmbPlace, before.place.code);
        }
        #endregion

        //订单选择界面
        private void btnOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (!m_IsOnline)
            {
                MessageBox.Show("当前网络处于断网状态，无法选择订单！");
                return;
            }
            PurchaseOrderSelectForm form = new PurchaseOrderSelectForm();
            form.MaterialArr = m_MaterialList.ToArray();
            form.SupplierArr = m_SupplierList.ToArray();
            form.MaterialCode = m_MaterialCode;
            form.SupplierCode = m_SupplierCode;
            if (form.ShowDialog() != DialogResult.OK)
                return;
            m_SelectedPurchaseOrder = form.SelectPurchaseOrder;
            if (m_SelectedPurchaseOrder == null)
                return;
            btnOrder.Text = m_SelectedPurchaseOrder.code;
            if (m_SelectedPurchaseOrder.material != null)
                cmbMaterial.SelectedItem = CommonHelper.FindDataInfoByKey(cmbMaterial, m_SelectedPurchaseOrder.material.code);
            if (m_SelectedPurchaseOrder.supplier != null)
                cmbSupplier.SelectedItem = CommonHelper.FindDataInfoByKey(cmbSupplier, m_SelectedPurchaseOrder.supplier.code);
            if (m_SelectedPurchaseOrder.place != null)
                cmbPlace.SelectedItem = CommonHelper.FindDataInfoByKey(cmbPlace, m_SelectedPurchaseOrder.place.code);
        }

        //委托
        public delegate void ShowWeightStatusHandler(string txt);
        //事件
        public event ShowWeightStatusHandler OnShowWeightStatusEvent;
        private void txtWeightStatus_TextChanged(object sender, EventArgs e)
        {
            if (m_DefaultDirectionCode.Contains(m_MaterialCode) && this.txtWeightStatus.Text == "第二次称重")
            {
                this.txtDefaultWeight.Properties.ReadOnly = false;
            }
            else
            {
                this.txtDefaultWeight.Properties.ReadOnly = true;
            }

            if (OnShowWeightStatusEvent != null)
            {
                OnShowWeightStatusEvent(this.txtWeightStatus.Text.Trim());
            }
        }

        private void txtIsDefaultTare_TextChanged(object sender, EventArgs e)
        {
            bool isDefaultTare = false;
            isDefaultTare = txtIsDefaultTare.Text == "是" ? true : false;
            if (OnIsDefaultTareEvent != null)
                OnIsDefaultTareEvent(isDefaultTare);
        }

        //委托
        public delegate void IsDefaultTareHandler(bool isDefaultTare);
        //事件
        public event IsDefaultTareHandler OnIsDefaultTareEvent;

        private void rgpBuckleType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rgpBuckleType.SelectedIndex == 0)
            {
    
                this.spBuckleRate.Properties.ReadOnly = false;
                this.txtBuckleWeight.Properties.ReadOnly = true;
            }
            else if (rgpBuckleType.SelectedIndex == 1)
            {
                this.spBuckleRate.Properties.ReadOnly = true;
                this.txtBuckleWeight.Properties.ReadOnly = false;
            }
            this.txtBuckleWeight.Text = "0";
            this.spBuckleRate.EditValue = 0;
            decimal grossWeight = decimal.Parse(this.txtGrossWeight.Text.Trim());
            decimal tareWeight = decimal.Parse(this.txtTareWeight.Text.Trim());
            if (grossWeight <= 0)
                return;
            decimal netWeight = grossWeight - tareWeight;
            this.txtNetWeight.Text = netWeight.ToString("0");
        }



    }
}
